//
// EpollDispatcher.h
//
// $Id: //poco/1.4/Net/include/Poco/Net/EpollDispatcher.h#1 $
//
// Library: Net
// Package: TCPServer
// Module:  EpollDispatcher
//
// Definition of the EpollDispatcher class.
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier:	BSL-1.0
//


#ifndef Net_EpollDispatcher_INCLUDED
#define Net_EpollDispatcher_INCLUDED


#include "Poco/Net/Net.h"
#include "Poco/Runnable.h"
#include "Poco/ThreadPool.h"
#include "Poco/Mutex.h"
#include "Poco/Net/SocketDefs.h"
#include "Poco/Net/EpollClientSocket.h"
#include "Poco/Net/EpollClientFactory.h"
#include "Poco/Thread.h"
#include <vector>
#include <map>

namespace Poco {
namespace Net {

class EpollServer;
class FdTimeOutThread;
enum EPOLL_MODE
{
	EPOLLMODE_ET,		/// edge triggered, the fd must be nonblocked
	EPOLLMODE_LT		/// level triggered	
};

class Net_API EpollDispatcher: public Poco::Runnable
	/// A helper class for TCPServer that dispatches
	/// connections to server connection threads.
{
public:
	EpollDispatcher(Poco::ThreadPool& threadPool, EpollClientFactory& factory,unsigned int timeoutSecond = 60);
		/// Creates the EpollDispatcher.
		/// timeout is also the max time a pooled thread can run
	
	~EpollDispatcher();
		/// Destroys the EpollDispatcher.
	
	virtual void run();
		/// Runs the dispatcher.
		
	void enqueue(int fd);
		/// Queues the given socket connection.
	
	void stop();
		/// Stops the dispatcher.

	void setEpollServer(EpollServer* server);
		/// needed when detect timeout or error fd to notify epollserver to stop watch
		/// optional to set
	
	/// monitor info no useful
	int queueSize() const
	{
		return m_queuesize;
	}
	
	
private:
	void dequeue(int fd);
		/// DeQueues the given socket connection.
	
	void checkCloseFd(int fd);
		/// check timeout fd

private:
	
	friend class EpollServer;
	friend class FdTimeOutThread;
	EpollDispatcher();
	EpollDispatcher(const EpollDispatcher&);
	EpollDispatcher& operator = (const EpollDispatcher&);
	mutable Poco::FastMutex			m_queueMutex;
	std::vector<int>					m_queue;
	std::map<int,EpollClientSocket*>	m_sockets;
	
	Poco::ThreadPool&               m_threadPool;
	EpollClientFactory& 			m_factory;
	Thread							m_thread;
	
	bool 							m_stopped;
		/// exit control
	EpollServer*					m_epollServer;
	unsigned int					m_timeout;				/// 可在队列中处理的时间限制，同时也是ThreadPool工作线程的超时时间
	std::map<int,unsigned long>		m_timeoutFds;
	int								m_maxFd;
	int								m_queuesize;
};


} } // namespace Poco::Net


#endif // Net_TCPServerDispatcher_INCLUDED
